#!/usr/bin/env python3
"""
Quantitative Advanced 项目初始化脚本
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def print_banner():
    """打印项目横幅"""
    print("=" * 60)
    print("🚀 Quantitative Advanced 项目初始化")
    print("=" * 60)
    print("股票恐贪指标分析系统")
    print("基于 Vue.js + Python Flask")
    print("=" * 60)

def check_python():
    """检查Python环境"""
    print("🔍 检查Python环境...")
    try:
        result = subprocess.run([sys.executable, '--version'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ Python版本: {result.stdout.strip()}")
            return True
        else:
            print("❌ Python环境检查失败")
            return False
    except Exception as e:
        print(f"❌ Python环境检查异常: {e}")
        return False

def check_node():
    """检查Node.js环境"""
    print("🔍 检查Node.js环境...")
    try:
        result = subprocess.run(['node', '--version'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ Node.js版本: {result.stdout.strip()}")
            return True
        else:
            print("❌ Node.js环境检查失败")
            return False
    except Exception as e:
        print(f"❌ Node.js环境检查异常: {e}")
        return False

def setup_backend():
    """设置后端环境"""
    print("\n🐍 设置Python后端环境...")
    
    backend_dir = Path("backend")
    if not backend_dir.exists():
        print("❌ 后端目录不存在")
        return False
    
    # 创建虚拟环境
    venv_dir = backend_dir / "venv"
    if not venv_dir.exists():
        print("📦 创建Python虚拟环境...")
        try:
            subprocess.run([sys.executable, '-m', 'venv', str(venv_dir)], 
                         check=True, cwd=backend_dir)
            print("✅ 虚拟环境创建成功")
        except subprocess.CalledProcessError as e:
            print(f"❌ 虚拟环境创建失败: {e}")
            return False
    
    # 激活虚拟环境并安装依赖
    print("📦 安装Python依赖...")
    try:
        if os.name == 'nt':  # Windows
            pip_path = venv_dir / "Scripts" / "pip.exe"
            activate_script = venv_dir / "Scripts" / "activate.bat"
        else:  # Linux/Mac
            pip_path = venv_dir / "bin" / "pip"
            activate_script = venv_dir / "bin" / "activate"
        
        # 安装依赖
        subprocess.run([str(pip_path), 'install', '-r', 'requirements.txt'], 
                      check=True, cwd=backend_dir)
        print("✅ Python依赖安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Python依赖安装失败: {e}")
        return False

def setup_frontend():
    """设置前端环境"""
    print("\n⚡ 设置Node.js前端环境...")
    
    # 检查package.json是否存在
    if not Path("package.json").exists():
        print("❌ package.json不存在")
        return False
    
    # 安装npm依赖
    print("📦 安装Node.js依赖...")
    try:
        subprocess.run(['npm', 'install'], check=True)
        print("✅ Node.js依赖安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Node.js依赖安装失败: {e}")
        return False

def create_env_file():
    """创建环境变量文件"""
    print("\n⚙️  创建环境变量文件...")
    
    backend_dir = Path("backend")
    env_example = backend_dir / "env.example"
    env_file = backend_dir / ".env"
    
    if env_example.exists() and not env_file.exists():
        try:
            shutil.copy(env_example, env_file)
            print("✅ 环境变量文件创建成功")
            print("📝 请根据需要编辑 backend/.env 文件")
            return True
        except Exception as e:
            print(f"❌ 环境变量文件创建失败: {e}")
            return False
    else:
        print("ℹ️  环境变量文件已存在或示例文件不存在")
        return True

def test_backend():
    """测试后端服务"""
    print("\n🧪 测试后端服务...")
    
    backend_dir = Path("backend")
    test_script = backend_dir / "test_api.py"
    
    if test_script.exists():
        try:
            # 激活虚拟环境并运行测试
            if os.name == 'nt':  # Windows
                python_path = backend_dir / "venv" / "Scripts" / "python.exe"
            else:  # Linux/Mac
                python_path = backend_dir / "venv" / "bin" / "python"
            
            result = subprocess.run([str(python_path), 'test_api.py'], 
                                  cwd=backend_dir, capture_output=True, text=True)
            
            if result.returncode == 0:
                print("✅ 后端测试成功")
                return True
            else:
                print("⚠️  后端测试失败，可能需要先启动后端服务")
                print(result.stderr)
                return False
        except Exception as e:
            print(f"❌ 后端测试异常: {e}")
            return False
    else:
        print("ℹ️  测试脚本不存在，跳过测试")
        return True

def print_next_steps():
    """打印后续步骤"""
    print("\n" + "=" * 60)
    print("🎉 项目初始化完成！")
    print("=" * 60)
    print("\n📋 后续步骤:")
    print("1. 启动后端服务:")
    print("   cd backend")
    print("   # Windows:")
    print("   venv\\Scripts\\activate")
    print("   # Linux/Mac:")
    print("   source venv/bin/activate")
    print("   python run.py")
    print("\n2. 启动前端服务:")
    print("   npm run dev")
    print("\n3. 或者使用启动脚本:")
    print("   # Windows:")
    print("   start.bat")
    print("   # Linux/Mac:")
    print("   ./start.sh")
    print("\n4. 访问应用:")
    print("   前端: http://localhost:5173")
    print("   后端API: http://localhost:5000")
    print("\n5. 查看文档:")
    print("   README.md - 项目主文档")
    print("   backend/README.md - 后端文档")
    print("=" * 60)

def main():
    """主函数"""
    print_banner()
    
    # 检查环境
    if not check_python():
        print("❌ Python环境检查失败，请安装Python 3.8+")
        return False
    
    if not check_node():
        print("❌ Node.js环境检查失败，请安装Node.js")
        return False
    
    # 设置环境
    if not setup_backend():
        print("❌ 后端环境设置失败")
        return False
    
    if not setup_frontend():
        print("❌ 前端环境设置失败")
        return False
    
    # 创建配置文件
    create_env_file()
    
    # 测试后端（可选）
    test_backend()
    
    # 打印后续步骤
    print_next_steps()
    
    return True

if __name__ == '__main__':
    try:
        success = main()
        if success:
            print("\n✅ 项目初始化成功完成！")
        else:
            print("\n❌ 项目初始化失败，请检查错误信息")
    except KeyboardInterrupt:
        print("\n\n⚠️  用户中断初始化过程")
    except Exception as e:
        print(f"\n❌ 初始化过程发生异常: {e}")
    
    input("\n按回车键退出...") 